﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MebApp.Launcher
{
    public static class ControlExtension
    {
        /// <summary>
        /// 设置属性
        /// </summary>
        /// <param name="control"></param>
        /// <param name="selector"></param>
        /// <param name="value"></param>
        public static void Property<T>(this Control control, Expression<Func<Control, T>> selector, T value)
        {
            if (!control.InvokeRequired)
            {
                var name = GetPropertyName(selector);
                control.GetType().GetProperty(name).SetValue(control, value);
            }
            else
                control.Invoke(new Action(() =>
                {
                    Property<T>(control, selector, value);
                }));
        }

        /// <summary>
        /// 获取属性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="control"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        public static T Property<T>(this Control control, Expression<Func<Control, T>> selector)
        {
            if (!control.InvokeRequired)
            {
                return selector.Compile().Invoke(control);
            }
            else
                return (T)control.Invoke(new Func<T>(() =>
                {
                    return Property<T>(control, selector);
                }));
        }

        public static string GetPropertyName<T, T2>(Expression<Func<T, T2>> expr)
        {
            var rtn = "";
            if (expr.Body is UnaryExpression)
            {
                rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
            }
            else if (expr.Body is MemberExpression)
            {
                rtn = ((MemberExpression)expr.Body).Member.Name;
            }
            else if (expr.Body is ParameterExpression)
            {
                rtn = ((ParameterExpression)expr.Body).Type.Name;
            }
            return rtn;
        }
    }
}
